/*
 *
 * @ProjectName:    my_umi_app
 * @Package:
 * @ClassName:      login_reducer
 * @Description:    把登录的业务逻辑分离出来
 * @Author:         SuPeiSen
 * @CreateDate:     2020/12/21 2:27 下午
 * @UpdateDate:     2020/12/21 2:27 下午
 * @UpdateRemark:   更新说明：
 * @Version:        1.0
 */

import { LoginModel } from '@/models/login';
import { RequestsStatus } from '@/utils/requests';
import { log } from '@/utils/app_fun';
import { message } from 'antd';
import { Local, LocalKey } from '@/utils/cache';
import { history } from '@@/core/history';

export interface LoginInitState {
  name?: string;
  pwd?: string;
  isLoading?: boolean;
  message?: string;
  data?: LoginModel;
}

export const loginReducer = (
  state: LoginInitState,
  action: {
    type: RequestsStatus;
    payload: LoginInitState;
  },
) => {
  switch (action.type) {
    case RequestsStatus.init:
      return {
        ...state,
        isLoading: true,
      };
    case RequestsStatus.success:
      const data = action.payload.data!;
      message.success(action.payload.message);
      // 保存token到本地
      Local.setStr(LocalKey.appToken, data.token);
      Local.setStr(LocalKey.refreshToken, data.refresh_token);
      setTimeout(() => {
        history.push('/admin');
      }, 2000);
      return {};
    case RequestsStatus.finally:
      return {
        ...state,
        isLoading: false,
      };
    default:
      return state;
  }
};
